var mysql = require("mysql");
var pool = null;

function DBError(message) {
    Error.call(this);
    this.name = "DBError";
    this.message = message || "DBError";
    this.statusCode = 200000;
}

function initMysqlPool() {
    pool = mysql.createPool({
        host: "127.0.0.1",
        user: "root",
        password: "123456",
        database: "confession"
    })
}

exports.query = function (sqlReq, callback) {
    if (!pool) {
        initMysqlPool();
    }

    if (!sqlReq) {
        throw new DBError("the sql is null");
    }

    var sql = sqlReq.sql || "";
    if (sql.length === 0) {
        throw new DBError("the sql is empty");
    }

    pool.getConnection(function (err, connection) {
        if (err) {
            throw err;
        }

        connection.config.queryFormat = function (query, values) {
            if (!values) return query;
            return query.replace(/\:(\w+)/g, function (txt, key) {
                if (values.hasOwnProperty(key)) {
                    return this.escape(values[key]);
                }
                return txt;
            }.bind(this));
        };

        connection.query(sql, sqlReq.params, function (err, rows) {
            connection.release();
            return callback(err, rows);
        });
    });
};